package hbasecli.controller;

import java.util.*;
import javax.annotation.Resource;

import hbasecli.model.json.param.CreateTableParam;
import hbasecli.model.json.JsonResponse;
import hbasecli.service.HBaseServiceForJson;
import hbasecli.model.json.TableObject;
import org.springframework.web.bind.annotation.*;

import static hbasecli.model.json.JsonResponse.failure;
import static hbasecli.model.json.JsonResponse.success;
import static org.springframework.util.CollectionUtils.isEmpty;
import static org.springframework.util.StringUtils.hasText;

@RestController
public class TableController {

    @Resource
    private HBaseServiceForJson service;

    @GetMapping("/api/tables")
    public JsonResponse<List<TableObject>> listTable(
            @RequestParam("connectionId") String connectionId
    ) {
        if (!hasText(connectionId)) {
            return failure("未知的连接");
        }
        return success(service.listTable(connectionId));
    }

    @PostMapping("/api/tables")
    public JsonResponse<Boolean> createTable(
            @RequestBody CreateTableParam param
    ) {
        String connectionId = param.getConnectionId();
        if (!hasText(connectionId)) {
            return failure("未知的连接");
        }
        String tableName = param.getTableName();
        if (!hasText(tableName)) {
            return failure("表名不可以为空值");
        }
        Set<String> families = new HashSet<>(param.getFamilies());
        if (isEmpty(families)) {
            return failure("至少需要一个列族");
        }
        Boolean deleteIfExists = param.getDeleteIfExists();
        return success(service.createTable(connectionId, tableName, families, Boolean.TRUE.equals(deleteIfExists)));
    }

    @DeleteMapping("/api/tables")
    public JsonResponse<Boolean> deleteTable(
            @RequestParam("connectionId") String connectionId,
            @RequestParam("name") String name
    ) {
        if (!hasText(connectionId)) {
            return failure("未知的连接");
        }
        if (!hasText(name)) {
            return failure("参数异常");
        }
        String[] tableNames = name.split(",");
        if (tableNames.length == 0) {
            return failure("至少需要一个表名");
        }
        for (String tableName : tableNames) {
            if (!hasText(tableName)) {
                return failure("表名 '" + tableName + "' 为空值");
            }
        }
        List<String> tableNameList = new ArrayList<>(tableNames.length);
        tableNameList.addAll(Arrays.asList(tableNames));
        return success(service.deleteTable(connectionId, tableNameList));
    }

}
